<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="传承人" prop="realName">
          <el-input
            v-model="queryParams.realName"
            placeholder="请输入传承人姓名"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
      <el-form-item label="项目名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="contact">
        <el-input
          v-model="queryParams.contact"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入驻时间" prop="createdAt">
        <el-date-picker clearable
          v-model="queryParams.createdAt"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择入驻时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['management:inheritor:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['management:inheritor:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['management:inheritor:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['management:inheritor:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inheritorList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="60">
        <template #default="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="传承人姓名" align="center" prop="realName" />
      <el-table-column label="项目名称" align="center" prop="itemId">
        <template #default="scope">
          <span>{{ getItemName(scope.row.itemId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="传承人简介" align="center" prop="biography" />
      <el-table-column label="联系方式" align="center" prop="contact" />
      <el-table-column label="佐证材料" align="center" width="120">
        <template #default="scope">
          <el-button type="primary" @click="viewProofMaterials(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="入驻时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button 
            link 
            type="primary" 
            icon="Edit" 
            @click="() => handleUpdate(scope.row)" 
            v-hasPermi="['management:inheritor:edit']"
          >修改</el-button>
          <el-button 
            link 
            type="primary" 
            icon="Delete" 
            @click="() => handleDelete(scope.row)" 
            v-hasPermi="['management:inheritor:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改传承人管理对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="inheritorRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="所属项目" prop="itemId">
          <el-select v-model="form.itemId" placeholder="请选择项目" clearable>
            <el-option
              v-for="item in itemList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="传承人姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入传承人姓名" />
        </el-form-item>
        <el-form-item label="传承人简介" prop="biography">
          <el-input v-model="form.biography" type="textarea" placeholder="请输入传承人简介" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="佐证材料" prop="proofMaterials">
          <image-upload 
            v-model="form.proofMaterials" 
            :limit="10" 
            :multiple="true"
            list-type="picture-card"
          />
          <div class="form-tip">支持上传多张图片，最多10张</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 佐证材料查看对话框 -->
    <el-dialog title="佐证材料详情" v-model="proofMaterialsDialogVisible" width="800px" append-to-body>
      <div class="proof-materials-content">
        <div v-if="currentProofMaterials && currentProofMaterials.length > 0" class="image-gallery">
          <el-row :gutter="10">
            <el-col :span="8" v-for="(image, index) in currentProofMaterials" :key="index">
              <el-image
                :src="image"
                :preview-src-list="currentProofMaterials"
                :initial-index="index"
                fit="cover"
                style="width: 100%; height: 150px; margin-bottom: 10px; border-radius: 4px;"
                preview-teleported
              />
            </el-col>
          </el-row>
        </div>
        <div v-else style="text-align: center; padding: 50px; color: #999;">
          暂无佐证材料
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="proofMaterialsDialogVisible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Inheritor">
import { listInheritor, getInheritor, delInheritor, addInheritor, updateInheritor } from "@/api/management/inheritor"
import { listItem } from "@/api/management/item"

const { proxy } = getCurrentInstance()

const inheritorList = ref([])
const itemList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const proofMaterialsDialogVisible = ref(false)
const currentProofMaterials = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    username: null,
    itemName: null,
    realName: null,
    contact: null,
    createdAt: null,
  },
  rules: {
    userId: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }
    ],
    itemId: [
      { required: true, message: "项目ID不能为空", trigger: "change" }
    ],
    realName: [
      { required: true, message: "传承人姓名不能为空", trigger: "blur" }
    ],
    biography: [
      { required: true, message: "传承人简介不能为空", trigger: "blur" }
    ],
    contact: [
      { required: true, message: "联系方式不能为空", trigger: "blur" }
    ],
    proofMaterials: [
      { 
        required: true, 
        message: "佐证材料不能为空", 
        trigger: "change",
        validator: (rule, value, callback) => {
          if (!value || (Array.isArray(value) && value.length === 0)) {
            callback(new Error('请至少上传一张佐证材料图片'))
          } else {
            callback()
          }
        }
      }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询传承人管理列表 */
function getList() {
  console.log('=== 获取列表数据 ===')
  console.log('当前时间:', new Date().toLocaleTimeString())
  console.log('查询参数:', queryParams.value)
  
  loading.value = true
  
  // 构建查询参数
  const params = { ...queryParams.value }
  
  // 如果输入了项目名称，需要转换为项目ID
  if (params.itemName) {
    const matchedItem = itemList.value.find(item => item.name === params.itemName)
    if (matchedItem) {
      params.itemId = matchedItem.id
    } else {
      // 如果没有找到匹配的项目，设置一个不存在的ID，确保查询结果为空
      params.itemId = -1
    }
    // 删除itemName参数，因为后端不识别
    delete params.itemName
  }
  
  listInheritor(params).then(response => {
    console.log('列表数据获取成功:', response)
    inheritorList.value = response.rows
    total.value = response.total
    loading.value = false
    
    // 确保按钮状态正确初始化
    console.log('重置按钮状态')
    ids.value = []
    single.value = true
    multiple.value = true
    
    console.log('列表刷新完成，按钮状态 - single:', single.value, 'multiple:', multiple.value)
  }).catch(error => {
    console.error('获取传承人列表失败:', error)
    loading.value = false
  })
}

/** 获取项目列表 */
function getItemList() {
  return listItem({}).then(response => {
    itemList.value = response.rows || []
  })
}

/** 初始化数据 - 先加载项目列表，再加载传承人列表 */
async function initData() {
  try {
    // 先加载项目列表
    await getItemList()
    // 再加载传承人列表
    getList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    // 即使项目列表加载失败，也要加载传承人列表
    getList()
  }
}

/** 根据项目ID获取项目名称 */
function getItemName(itemId) {
  const item = itemList.value.find(item => item.id === itemId)
  return item ? item.name : (itemList.value.length === 0 ? '加载中...' : '未知项目')
}

// 取消按钮
function cancel() {
  console.log('=== 取消按钮被点击 ===')
  console.log('当前时间:', new Date().toLocaleTimeString())
  console.log('关闭对话框前的状态 - open.value:', open.value)
  open.value = false
  console.log('关闭对话框后的状态 - open.value:', open.value)
  reset()
}

// 表单重置
function reset() {
  console.log('=== 表单重置函数被调用 ===')
  console.log('当前时间:', new Date().toLocaleTimeString())
  console.log('重置前的表单数据:', JSON.stringify(form.value, null, 2))
  
  form.value = {
    id: null,
    userId: null,
    itemId: null,
    realName: null,
    biography: null,
    contact: null,
    proofMaterials: [],  // 改为空数组，适配图片上传组件
    createdAt: null,
    updatedAt: null
  }
  
  console.log('重置后的表单数据:', JSON.stringify(form.value, null, 2))
  
  // 重置表单验证状态
  if (proxy.$refs["inheritorRef"]) {
    console.log('重置表单验证状态')
    proxy.resetForm("inheritorRef")
  } else {
    console.log('表单引用不存在，跳过验证重置')
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  console.log('=== 表格选择状态变化 ===')
  console.log('当前时间:', new Date().toLocaleTimeString())
  console.log('选中的数据:', selection)
  console.log('选中数量:', selection.length)
  
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
  
  console.log('更新后的状态:')
  console.log('- ids:', ids.value)
  console.log('- single (修改按钮禁用):', single.value)
  console.log('- multiple (删除按钮禁用):', multiple.value)
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加传承人管理"
}

/** 修改按钮 */
function handleUpdate(row) {
  console.log('=== 修改按钮被点击 ===')
  console.log('当前时间:', new Date().toLocaleTimeString())
  console.log('点击的行数据:', JSON.stringify(row, null, 2))
  console.log('row.id:', row.id)
  console.log('row._id:', row._id)
  
  // 重置表单状态
  reset()
  
  const id = row.id || row._id
  console.log('获取到的ID:', id)
  
  if (!id) {
    console.error('无法获取传承人ID')
    proxy.$modal.msgError("无法获取传承人ID")
    return
  }
  
  console.log('准备调用getInheritor接口，参数:', id)
  
  getInheritor(id).then(response => {
    console.log('getInheritor接口返回数据:', response)
    
    if (response && response.data) {
      form.value = { ...response.data }
      console.log('设置表单数据:', form.value)
      open.value = true
      title.value = "修改传承人管理"
      console.log('对话框已打开，标题:', title.value)
    } else {
      console.error('接口返回数据格式错误:', response)
      proxy.$modal.msgError("获取传承人信息失败")
    }
  }).catch(error => {
    console.error('getInheritor接口调用失败:', error)
    proxy.$modal.msgError("获取传承人信息失败: " + (error.message || error))
  })
}

/** 提交按钮 */
function submitForm() {
  console.log('=== 提交表单开始 ===')
  console.log('当前时间:', new Date().toLocaleTimeString())
  console.log('提交表单，当前表单数据:', JSON.stringify(form.value, null, 2))
  
  proxy.$refs["inheritorRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        console.log('执行修改操作，ID:', form.value.id)
        updateInheritor(form.value).then(response => {
          console.log('修改成功，响应:', response)
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          
          // 重置表格选择状态，确保按钮状态正确
          console.log('重置表格选择状态')
          ids.value = []
          single.value = true
          multiple.value = true
          
          // 刷新列表
          getList()
          
          console.log('修改操作完成，按钮状态 - single:', single.value, 'multiple:', multiple.value)
        }).catch(error => {
          console.error('修改失败:', error)
          proxy.$modal.msgError('修改失败: ' + (error.message || '未知错误'))
        })
      } else {
        console.log('执行新增操作')
        addInheritor(form.value).then(response => {
          console.log('新增成功，响应:', response)
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          
          // 重置表格选择状态，确保按钮状态正确
          console.log('重置表格选择状态')
          ids.value = []
          single.value = true
          multiple.value = true
          
          // 刷新列表
          getList()
          
          console.log('新增操作完成，按钮状态 - single:', single.value, 'multiple:', multiple.value)
        }).catch(error => {
          console.error('新增失败:', error)
          proxy.$modal.msgError('新增失败: ' + (error.message || '未知错误'))
        })
      }
    } else {
      console.log('表单验证失败')
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  let message = ''
  
  if (row.id) {
    // 单个删除 - 计算当前行的序号
    const currentIndex = inheritorList.value.findIndex(item => item.id === row.id)
    const serialNumber = (queryParams.value.pageNum - 1) * queryParams.value.pageSize + currentIndex + 1
    message = `是否确认删除序号为"${serialNumber}"的数据项？`
  } else {
    // 批量删除 - 计算所有选中行的序号
    const serialNumbers = []
    ids.value.forEach(id => {
      const currentIndex = inheritorList.value.findIndex(item => item.id === id)
      if (currentIndex !== -1) {
        const serialNumber = (queryParams.value.pageNum - 1) * queryParams.value.pageSize + currentIndex + 1
        serialNumbers.push(serialNumber)
      }
    })
    message = `是否确认删除序号为"${serialNumbers.join('、')}"的数据项？`
  }
  
  proxy.$modal.confirm(message).then(function() {
    return delInheritor(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 查看佐证材料 */
function viewProofMaterials(row) {
  // 处理图片数据格式
  if (row.proofMaterials) {
    if (typeof row.proofMaterials === 'string') {
      try {
        // 尝试解析JSON格式
        currentProofMaterials.value = JSON.parse(row.proofMaterials)
      } catch (e) {
        // 如果解析失败，按照逗号分隔的字符串处理
        currentProofMaterials.value = row.proofMaterials.split(',').map(url => url.trim()).filter(url => url)
      }
    } else if (Array.isArray(row.proofMaterials)) {
      currentProofMaterials.value = row.proofMaterials
    } else {
      currentProofMaterials.value = []
    }
  } else {
    currentProofMaterials.value = []
  }
  proofMaterialsDialogVisible.value = true
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('management/inheritor/export', {
    ...queryParams.value
  }, `inheritor_${new Date().getTime()}.xlsx`)
}

initData()
</script>
